package com.atwu.wl2022.service.impl;

import com.atwu.wl2022.entity.Diary;
import com.atwu.wl2022.mapper.DiaryMapper;
import com.atwu.wl2022.service.IDiaryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wule
 * @since 2022-06-12
 */
@Service
public class DiaryServiceImpl extends ServiceImpl<DiaryMapper, Diary> implements IDiaryService {


	@Autowired
	DiaryMapper diaryMapper;

	@Override
	public ArrayList<List<Diary>> getDiaryList() {
		List<Diary> list = diaryMapper.selectList(new QueryWrapper<Diary>().orderByDesc("date_time"));
		return diaryListGroup(list);
	}

	public ArrayList<List<Diary>> diaryListGroup(List<Diary> diarys) {
		int size = diarys.size();
		//最后返回的集合
		ArrayList<List<Diary>> diaryList = new ArrayList<>();
		//创建中间量
		int temp = 0;
		//创建一个暂存集合
		ArrayList<Diary> list = new ArrayList<>();

		for (Diary diary : diarys) {
			//获取当前日期的所在年份
			int year = Integer.parseInt(String.format("%tY", diary.getDateTime()));
			if (temp == 0) {
				//第一次遍历
				list.add(diary);
				//将当前的年份赋给中间量
				temp = year;
			} else {
				//当当前年份不等于上一个的年份，说明到了一个新的年
				if (year != temp) {
					//1、将封装了1年信息的集合装入主集合中
					diaryList.add(list);
					//2、将暂存集合清空
					list = new ArrayList<>();
					//3、将当前的年份赋给中间量
					temp = year;
					//4、将当前加入集合
					list.add(diary);
				} else {
					//当前的年份等于上一个的年份，将这个装进暂存集合中，继续遍历
					list.add(diary);
					if (diary.equals(diarys.get(size - 1))) {
						diaryList.add(list);
					}
				}
			}
		}
		return diaryList;
	}

}
